package com.hjh.gameforum.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.CoercionAction;
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.hjh.gameforum.enums.Gender;
import com.hjh.gameforum.enums.UserStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 允许将空字符串转换为 null 或默认值
        mapper.coercionConfigFor(java.lang.Enum.class)
              .setCoercion(CoercionInputShape.String, CoercionAction.AsNull);

        // 自定义 Enum 反序列化行为
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Gender.class, new JsonDeserializer<Gender>() {
            @Override
            public Gender deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                String value = p.getValueAsString();
                if (value == null || value.isBlank()) {
                    return Gender.UNKNOWN;
                }
                try {
                    return Gender.valueOf(value.toUpperCase());
                } catch (IllegalArgumentException e) {
                    return Gender.UNKNOWN;
                }
            }
        });
        module.addDeserializer(UserStatus.class, new JsonDeserializer<UserStatus>() {
            @Override
            public UserStatus deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                String value = p.getValueAsString();
                if (value == null || value.isBlank()) {
                    return UserStatus.active;
                }
                try {
                    return UserStatus.valueOf(value.toUpperCase());
                } catch (IllegalArgumentException e) {
                    return UserStatus.active;
                }
            }
        });

        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(module);
        return mapper;
    }
}